const { songs } = require('../../data/songs.js');

Page({
  data: {
    currentTab: 1,
    currentSong: null,
    currentIndex: 0,
    playlist: [],
    lyrics: [],
    currentLyricIndex: 0,
    progress: 0,
    currentTime: '00:00',
    duration: '04:27',
    isSeeking: false,
    isPlaying: false,
    playMode: 'loop', // 'loop', 'single', 'random'
    playModeIcon: 'loop', // 播放模式图标
    slideDirection: '', // 添加滑动方向状态
    listeningCount: 999,
    isUserScrolling: false, // 添加用户是否正在滚动的标记
    userScrollTimeout: null // 用于跟踪用户滚动超时
  },

  // 添加页面卸载标记
  isPageUnloaded: false,

  onLoad() {
    this.isPageUnloaded = false;
    const app = getApp();
    const playerManager = app.globalData.playerManager;
    
    // 直接初始化，不使用 nextTick
    this.initializePlayer(playerManager);
  },

  // 安全的 setData 方法
  safeSetData(data) {
    if (!this.isPageUnloaded) {
      this.setData(data);
    }
  },

  initializePlayer(playerManager) {
    const currentSong = playerManager.currentSong || {
      id: '1',
      title: '示例歌曲',
      artist: '未知歌手',
      cover: '/assets/images/default-cover.png',
      lyrics: []
    };
    
    const songList = playerManager.playlist || songs || [];
    const currentIndex = songList.findIndex(song => song.id === currentSong.id);
    
    // 使用安全的 setData
    this.safeSetData({
      currentSong,
      isPlaying: playerManager.isPlaying,
      playlist: songList,
      currentIndex: currentIndex >= 0 ? currentIndex : 0,
      playMode: playerManager.playMode || 'loop',
      playModeIcon: this.getPlayModeIcon(playerManager.playMode || 'loop'),
      progress: 0,
      currentTime: '00:00',
      duration: this.formatTime(playerManager.audioManager?.duration || 0),
      lyrics: [],
      currentLyricIndex: 0
    });

    // 如果有���词，再处理歌词
    if (currentSong.lyrics && Array.isArray(currentSong.lyrics)) {
      const processedLyrics = this.processLyrics(currentSong.lyrics);
      this.safeSetData({ lyrics: processedLyrics });
    }

    // 设置时间更新监听
    this.lastUpdateTime = 0;
    const THROTTLE_INTERVAL = 200;

    playerManager.audioManager.onTimeUpdate(() => {
      if (this.isPageUnloaded) return;
      
      const now = Date.now();
      if (now - this.lastUpdateTime < THROTTLE_INTERVAL) return;
      this.lastUpdateTime = now;
      
      if (!this.data.isSeeking) {
        this.updatePlaybackProgress();
      }
    });

    // 添加播放状态监听
    playerManager.watchPlayStatus(this.updatePlayStatus.bind(this));
  },

  updatePlaybackProgress() {
    if (this.isPageUnloaded || !this.data.isSeeking) {
      const playerManager = getApp().globalData.playerManager;
      const currentTime = playerManager.audioManager.currentTime || 0;
      const duration = playerManager.audioManager.duration || 0;
      
      if (duration > 0) {
        const updateData = {
          progress: (currentTime / duration) * 100,
          currentTime: this.formatTime(currentTime),
          duration: this.formatTime(duration)
        };

        if (this.data.lyrics && this.data.lyrics.length > 0) {
          updateData.currentLyricIndex = this.findCurrentLyricIndex(currentTime);
        }

        this.safeSetData(updateData);

        if (this.data.currentTab === 2 && this.data.lyrics && this.data.lyrics.length > 0) {
          this.scrollToCurrentLyric();
        }
      }
    }
  },

  findCurrentLyricIndex(currentTime) {
    const { lyrics } = this.data;
    if (!lyrics?.length) return 0;
    
    // 缓存上一次的索引
    if (this.lastIndex !== undefined) {
      const current = lyrics[this.lastIndex];
      const next = lyrics[this.lastIndex + 1];
      
      // 如果当前时间在上一次���区间内，直接返回
      if (current && next) {
        if (currentTime >= current.time && currentTime < next.time) {
          return this.lastIndex;
        }
      }
    }
    
    // 二分查找优化
    let left = 0;
    let right = lyrics.length - 1;
    
    while (left <= right) {
      const mid = (left + right) >> 1;
      const time = lyrics[mid].time;
      
      if (time <= currentTime && (!lyrics[mid + 1] || lyrics[mid + 1].time > currentTime)) {
        this.lastIndex = mid;
        return mid;
      }
      
      if (time > currentTime) {
        right = mid - 1;
      } else {
        left = mid + 1;
      }
    }
    
    return 0;
  },

  scrollToCurrentLyric() {
    // 如果不在歌词页面或用户正在滚动，不执行滚动
    if (this.data.currentTab !== 2 || this.data.isUserScrolling) return;
    
    // 使用防抖
    if (this.scrollTimer) {
      clearTimeout(this.scrollTimer);
    }

    this.scrollTimer = setTimeout(() => {
      // 计算滚动位置
      const itemHeight = 50;  // 每个歌词项的固定高度
      const scrollTop = this.data.currentLyricIndex * itemHeight;
      
      try {
        const query = wx.createSelectorQuery();
        query.select('.lyrics-container')
          .node()
          .exec(res => {
            const scrollView = res[0]?.node;
            if (scrollView) {
              scrollView.scrollTo({
                top: scrollTop,
                behavior: 'smooth',
                duration: 300
              });
            }
          });
      } catch (error) {
        console.error('歌词滚动失败:', error);
      }
    }, 100);
  },

  // 处理用户滚动开始
  onLyricsScroll() {
    if (this.data.userScrollTimeout) {
      clearTimeout(this.data.userScrollTimeout);
    }
    
    this.setData({ isUserScrolling: true });
    
    // 设置一个定时器，在用户停止滚动3秒后恢复自动滚动
    const timeout = setTimeout(() => {
      this.setData({ isUserScrolling: false });
    }, 3000);
    
    this.setData({ userScrollTimeout: timeout });
  },

  onUnload() {
    // 设置页面卸载标记
    this.isPageUnloaded = true;
    
    // 清除定时器
    if (this.scrollTimer) {
      clearTimeout(this.scrollTimer);
    }
    if (this.statusUpdateTimer) {
      clearTimeout(this.statusUpdateTimer);
    }
    if (this.data.userScrollTimeout) {
      clearTimeout(this.data.userScrollTimeout);
    }
    
    // 移除监听
    const app = getApp();
    app.globalData.playerManager.unwatchPlayStatus(this.updatePlayStatus.bind(this));
  },

  // 更新播放状态
  updatePlayStatus(globalData) {
    if (this.isPageUnloaded || !globalData) return;
    
    const currentSong = globalData.currentSong || this.data.currentSong;
    const isPlaying = globalData.isPlaying;
    
    if (currentSong.id !== this.data.currentSong.id) {
      const lyrics = currentSong.lyrics || [];
      const processedLyrics = this.processLyrics(lyrics);
      
      this.safeSetData({
        lyrics: processedLyrics,
        currentLyricIndex: 0,
        currentSong,
        isPlaying
      });
    } else {
      this.safeSetData({
        currentSong,
        isPlaying
      });
    }
  },

  // 切换标签
  switchTab(e) {
    const tab = parseInt(e.currentTarget.dataset.tab);
    if (this.data.currentTab === tab) {
      return; // 如果点击当前标签，不任何操作
    }
    this.setData({
      currentTab: tab
    });
  },

  // 滑动切换
  onSwiperChange(e) {
    const current = e.detail.current;
    if (this.data.currentTab === current) {
      return; // 如果是当前页，不做任何操作
    }
    this.setData({
      currentTab: current
    });
  },

  // 返回上一页
  onBackTap() {
    wx.navigateBack();
  },

  // 进度条拖动开始
  onSliderDragStart() {
    this.setData({ isSeeking: true });
  },

  // 进度条变化
  onSliderChange(e) {
    const playerManager = getApp().globalData.playerManager;
    const progress = e.detail.value;
    const currentTime = (progress / 100) * playerManager.audioManager.duration;
    playerManager.audioManager.seek(currentTime);
    this.setData({
      progress,
      currentTime: this.formatTime(currentTime),
      isSeeking: false
    });
  },
  // 格式化时间
  formatTime(seconds) {
    const minutes = Math.floor(seconds / 60);
    seconds = Math.floor(seconds % 60);
    return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
  },

  // 获取播放模式图标
  getPlayModeIcon(mode) {
    const icons = {
      loop: 'loop',
      single: 'single-loop',
      random: 'shuffle'
    };
    return icons[mode] || 'loop';
  },

  // 播放/暂停
  onPlayPauseTap() {
    const app = getApp();
    const playerManager = app.globalData.playerManager;
    
    // 使用 togglePlay 方法来切换播放状态
    playerManager.togglePlay();
    
    // 直接更新本地状态，避免重复设置
    this.setData({
      isPlaying: playerManager.isPlaying
    });
  },

  // 上一首
  onPrevTap() {
    if (this.isPageUnloaded) return;
    
    const app = getApp();
    const playerManager = app.globalData.playerManager;
    
    const newIndex = this.data.currentIndex > 0 ? this.data.currentIndex - 1 : this.data.playlist.length - 1;
    const newSong = this.data.playlist[newIndex];
    
    this.safeSetData({ 
      slideDirection: 'right',
      currentSong: newSong,
      currentIndex: newIndex,
      isPlaying: true,
      currentTime: '00:00',
      progress: 0
    });
    
    playerManager.audioManager.src = newSong.src;
    playerManager.audioManager.title = newSong.title;
    playerManager.audioManager.singer = newSong.artist;
    playerManager.audioManager.coverImgUrl = newSong.cover;
    
    playerManager.currentSong = newSong;
    playerManager.isPlaying = true;
    playerManager.audioManager.play();
    
    this.processLyrics(newSong.lyrics || []);
    
    setTimeout(() => {
      if (!this.isPageUnloaded) {
        this.safeSetData({ slideDirection: '' });
      }
    }, 500);
  },

  // 下一首
  onNextTap() {
    if (this.isPageUnloaded) return;
    
    const app = getApp();
    const playerManager = app.globalData.playerManager;
    
    const newIndex = (this.data.currentIndex + 1) % this.data.playlist.length;
    const newSong = this.data.playlist[newIndex];
    
    this.safeSetData({ 
      slideDirection: 'left',
      currentSong: newSong,
      currentIndex: newIndex,
      isPlaying: true,
      currentTime: '00:00',
      progress: 0
    });
    
    playerManager.audioManager.src = newSong.src;
    playerManager.audioManager.title = newSong.title;
    playerManager.audioManager.singer = newSong.artist;
    playerManager.audioManager.coverImgUrl = newSong.cover;
    
    playerManager.currentSong = newSong;
    playerManager.isPlaying = true;
    playerManager.audioManager.play();
    
    this.processLyrics(newSong.lyrics || []);
    
    setTimeout(() => {
      if (!this.isPageUnloaded) {
        this.safeSetData({ slideDirection: '' });
      }
    }, 500);
  },

  // 处理歌词的辅助函数
  processLyrics(lyrics = []) {
    try {
      const processedLyrics = [];
      
      if (Array.isArray(lyrics)) {
        lyrics.forEach((text, index) => {
          if (text && text.trim()) {
            processedLyrics.push({
              text: text.trim(),
              time: index * 4,
              isEnglish: /^[A-Za-z\s\W]+$/.test(text),
              isInfo: text.includes(':')
            });
          }
        });
      }
      
      wx.nextTick(() => {
        this.setData({
          lyrics: processedLyrics,
          currentLyricIndex: 0
        });
      });
      
      return processedLyrics;
    } catch (error) {
      console.error('处理歌词出错:', error);
      return [];
    }
  },

  // 切换播放模式
  onPlayModeTap() {
    const modes = ['loop', 'single', 'random'];
    const currentIndex = modes.indexOf(this.data.playMode);
    const nextMode = modes[(currentIndex + 1) % modes.length];
    
    getApp().globalData.playerManager.setPlayMode(nextMode);
    
    this.setData({
      playMode: nextMode,
      playModeIcon: this.getPlayModeIcon(nextMode)
    });

    // 显示提示
    const modeText = {
      loop: '列表循环',
      single: '单曲循环',
      random: '随机播放'
    };
    wx.showToast({
      title: modeText[nextMode],
      icon: 'none'
    });
  },

  // 喜欢/取消喜欢
  onLikeTap() {
    const { currentSong } = this.data;
    currentSong.isLiked = !currentSong.isLiked;
    this.setData({ currentSong });

    wx.showToast({
      title: currentSong.isLiked ? '已添加到我欢的音乐' : '已取消喜欢',
      icon: 'none'
    });
  },

  // 下载
  onDownloadTap() {
    wx.showToast({
      title: '开始下载...',
      icon: 'loading'
    });
  },

  // 评论
  onCommentTap() {
    wx.showToast({
      title: '评论功开���中',
      icon: 'none'
    });
  },

  // 更多操作
  onMoreTap() {
    wx.showActionSheet({
      itemList: ['分享', '歌手详情', '专辑详情', '举报'],
      success: (res) => {
        console.log(res.tapIndex);
      }
    });
  },

  // 显示播放列表
  onPlaylistTap() {
    this.setData({ currentTab: 1 });
  },

  // 点击歌曲项
  onSongTap(e) {
    if (this.isPageUnloaded) return;
    
    const song = e.currentTarget.dataset.song;
    const app = getApp();
    const playerManager = app.globalData.playerManager;
    
    if (song.id === this.data.currentSong.id) {
      playerManager.togglePlay();
      return;
    }
    
    const newIndex = this.data.playlist.findIndex(s => s.id === song.id);
    
    this.safeSetData({
      currentSong: song,
      currentIndex: newIndex,
      isPlaying: true,
      currentTime: '00:00',
      progress: 0
    });
    
    playerManager.audioManager.src = song.src;
    playerManager.audioManager.title = song.title;
    playerManager.audioManager.singer = song.artist;
    playerManager.audioManager.coverImgUrl = song.cover;
    
    playerManager.currentSong = song;
    playerManager.isPlaying = true;
    playerManager.audioManager.play();
    
    this.processLyrics(song.lyrics || []);
  },

  // 优化播放状态监听
  watchPlayStatus() {
    const playerManager = getApp().globalData.playerManager;
    
    // 使用节流处理状态更新
    if (this.statusUpdateTimer) {
      clearTimeout(this.statusUpdateTimer);
    }
    
    this.statusUpdateTimer = setTimeout(() => {
      this.setData({
        isPlaying: playerManager.isPlaying
      });
    }, 100);
  },

  // 点击歌手名字
  onArtistTap() {
    const { currentSong } = this.data;
    if (currentSong && currentSong.artist) {
      wx.navigateTo({
        url: `/pages/artist/artist?name=${encodeURIComponent(currentSong.artist)}`
      });
    }
  },
}); 